package com.xiaomaoguai.fcp.pre.kepler.router.rpc.server.servlet.request;

import io.netty.buffer.ByteBufInputStream;
import io.netty.handler.codec.http.FullHttpRequest;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import java.io.IOException;

import static com.google.common.base.Preconditions.checkNotNull;

public class NettyServletInputStream extends ServletInputStream {


	private ByteBufInputStream in;

	private ReadListener readListener;

	public NettyServletInputStream(FullHttpRequest request) {
		this.in = new ByteBufInputStream(request.content());
	}

	@Override
	public int read() throws IOException {
		return in.read();
	}

	@Override
	public int read(byte[] buf) throws IOException {
		return in.read(buf);
	}

	@Override
	public int read(byte[] buf, int offset, int len) throws IOException {
		return in.read(buf, offset, len);
	}

	/**
	 * 跳过n个字节
	 */
	@Override
	public long skip(long n) throws IOException {
		return in.skip(n);
	}

	/**
	 * @return 可读字节数
	 */
	@Override
	public int available() throws IOException {
		return in.available();
	}

	@Override
	public void close() throws IOException {
		in.close();
	}

	@Override
	public int readLine(byte[] b, int off, int len) throws IOException {
		checkNotNull(b);
		return super.readLine(b, off, len); //模板方法，会调用当前类实现的read()方法
	}

	/**
	 * @return 可用为true 反之false
	 */
	@Override
	public boolean isFinished() {
		boolean flag = false;
		try {
			flag = (in.available() == 0);
		} catch (IOException e) {
		}
		return flag;
	}

	@Override
	public boolean isReady() {
		boolean flag = false;
		try {
			flag = (in.available() > 0);
		} catch (IOException e) {
		}
		return flag;
	}

	public ReadListener getReadListener() {
		return readListener;
	}

	@Override
	public void setReadListener(ReadListener readListener) {
		this.readListener = checkNotNull(readListener);
		;
	}


}